package org.example.com.editor.command.editorCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.command.Undoable;
import org.example.com.editor.command.commandHistory.CommandHistoryItem;
import org.example.com.editor.editor.Editor;
import org.example.com.editor.editor.TextEditor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class InsertCommand implements Command, Undoable {
    int lineNum;
    int colNum;
    String insertedText;

    private final LogManager logManager;

    public InsertCommand(LogManager logManager) {
        this.logManager = logManager;
    }



    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        Map<String, Object> params = new HashMap<>();
        if (editor == null) {
            ui.printError("没有活动文件，请先打开或新建文件");
            return;
        }

        String[] args = ui.getCommandArgs();
        if (args.length != 3) {
            ui.printError("用法：insert <行号:列号> <文本内容>（例如：insert 2:3 \"hello\\nworld\"）");
            return;
        }

        // 解析line:col参数（args[1]）
        String[] lineCol = args[1].split(":", 2); // 按:分割为行号和列号
        if (lineCol.length != 2) {
            ui.printError("位置格式错误，请使用\"行号:列号\"（例如：2:3）");
            return;
        }

        try {
            lineNum = Integer.parseInt(lineCol[0]);
            colNum = Integer.parseInt(lineCol[1]);
        } catch (NumberFormatException e) {
            ui.printError("行号和列号必须是整数（例如：2:3）");
            return;
        }

        // 解析文本内容（args[2]，去掉首尾引号）
        String rawText = args[2];
        if (rawText.length() < 2 || !rawText.startsWith("\"") || !rawText.endsWith("\"")) {
            ui.printError("文本内容必须用双引号包裹（例如：\"content\\nnew line\"）");
            return;
        }
        insertedText = rawText.substring(1, rawText.length() - 1); // 去掉引号

        params.put("lineNum", lineNum);
        params.put("colNum", colNum);
        params.put("insertedText", insertedText);

        insert(ui, editor, params);
        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void undo( Editor editor, ConsoleUI ui,Map<String, Object> params) {
        lineNum = (int) params.get("lineNum");
        colNum = (int) params.get("colNum");
        insertedText = (String) params.get("insertedText");

        // 计算删除长度
        // 删除插入的文本
        ((TextEditor)editor).undoInsert(lineNum, colNum, insertedText);
    }

    @Override
    public void redo(Workspace workspace, ConsoleUI ui, Map<String, Object> params) {
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        lineNum = (int) params.get("lineNum");
        colNum = (int) params.get("colNum");
        insertedText = (String) params.get("insertedText");

        insert(ui, editor, params);
    }

    @Override
    public String getName() {
        return "insert";
    }

    private void insert(ConsoleUI ui, TextEditor editor,Map<String, Object> params) {
        try {
            editor.insert(lineNum, colNum, insertedText);
            editor.recordCommand(new CommandHistoryItem(this, params));
        } catch (IllegalArgumentException e) {
            ui.printError(e.getMessage());
        } catch (Exception e) {
            ui.printError("插入操作失败：" + e.getMessage());
        }
    }
}